import datetime

import sqlalchemy
from flask import Blueprint, request, session, redirect, url_for, jsonify, render_template, json
from sqlalchemy import func, or_, desc

from models import User, db, Bottle

bp = Blueprint('bottle', __name__)


@bp.route('/setbottle', methods=['GET', 'POST'])
def setBottle():
    # 未登录
    if 'username' not in session:
        return jsonify({'error': '你还没有到海边~'})

    if request.method == 'POST':
        data = request.json
        username = data.get('username')
        userid = data.get('userid')
        content = data.get('content')

        if len(username) < 1 or len(userid) < 1 or len(content) < 1:
            return jsonify({'error': '瓶子未封闭完整'})
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        client_ip = request.remote_addr
        bottle = Bottle(content=content, setuser=username, setip=client_ip, settime=current_time, ashore=0)
        db.session.add(bottle)
        try:
            db.session.commit()
            return jsonify({'success': '成功丢到海里 >_<'})
        except sqlalchemy.exc.SQLAlchemyError:
            return jsonify({'error': '核废水腐蚀了你的漂流瓶，请稍后重试'})

    return jsonify({'error': '核废水流到了大海，请稍后重试'})


@bp.route('/getbottle', methods=['GET', 'POST'])
def getBottle():
    # 未登录
    if 'username' not in session:
        return jsonify({'error': '你还没有到海边~'})

    if request.method == 'POST':
        data = request.json
        username = data.get('username')
        userid = data.get('userid')
        if len(username) < 1 or len(userid) < 1:
            return jsonify({'error': '你是谁???'})

        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        client_ip = request.remote_addr
        # 从数据库中随机获取一条 ashore=0 的数据
        bottle = Bottle.query.filter_by(ashore=0).order_by(func.random()).first()

        if not bottle:
            # 数据库中没有满足条件的记录
            return jsonify({'error': '没有漂流瓶了'})

        try:
            # 更新数据库中的数据
            bottle.gettime = current_time
            bottle.getip = client_ip
            bottle.getuser = username  # 请确保 username 变量已定义
            bottle.ashore = 1
            bottle_id = bottle.id
            # 提交更改到数据库
            db.session.commit()

            # 返回更新后的数据
            return jsonify({
                'state': 200,
                'content': bottle.content,
                'settime': bottle.settime,
                'setuser': bottle.setuser,
                'setip': bottle.setip,
                'bottleid': bottle_id
            })
        except sqlalchemy.exc.SQLAlchemyError:
            return jsonify({'error': '核废水腐蚀了你的漂流瓶，请稍后重试'})

    return jsonify({'error': '核废水流到了大海，请稍后重试'})


# 抛回海里
@bp.route('/rebottle', methods=['GET', 'POST'])
def reBottle():
    # 未登录
    if 'username' not in session:
        return jsonify({'error': '你还没有到海边~'})

    if request.method == 'POST':
        data = request.json
        username = data.get('username')
        bottleid = data.get('bottleid')
        if len(username) < 1 or len(str(bottleid)) < 1:
            return jsonify({'error': '你是谁???'})

        bottle = Bottle.query.get(bottleid)
        try:
            bottle.gettime = ''
            bottle.getip = ''
            bottle.getuser = ''
            bottle.ashore = 0
            db.session.commit()
            # 返回更新后的数据
            return jsonify({'success': '抛回成功~'})
        except sqlalchemy.exc.SQLAlchemyError:
            return jsonify({'error': '核废水腐蚀了你的漂流瓶，请稍后重试'})

    return jsonify({'error': '核废水流到了大海，请稍后重试'})


@bp.route('/getlist', methods=['GET', 'POST'])
def getList():
    # 未登录
    if 'username' not in session:
        return jsonify({'error': '你还没有到海边~'})

    if request.method == 'POST':
        data = request.json
        username = data.get('username')
        userid = data.get('userid')
        if len(username) < 1 or len(userid) < 1:
            return jsonify({'error': '你是谁???'})

        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        client_ip = request.remote_addr
        # bottles = Bottle.query.filter(or_(Bottle.setuser == username, Bottle.getuser == username)).order_by(func.random()).all()
        bottles = Bottle.query.filter(or_(Bottle.setuser == username, Bottle.getuser == username)). \
            order_by(desc(Bottle.gettime), desc(Bottle.settime)).all()
        if not bottles:
            # 数据库中没有满足条件的记录
            return jsonify({'error': '你还没有漂流瓶'})

        try:
            data = []
            for bottle in bottles:
                if username != bottle.setuser:
                    data.append({
                        'content': bottle.content,
                        'settime': bottle.settime,
                        'setuser': bottle.setuser,
                        'type': '我捞的',
                        'id': bottle.id
                    })
                else:
                    data.append({
                        'content': bottle.content,
                        'settime': bottle.settime,
                        'setuser': bottle.setuser,
                        'type': '我丢的',
                        'id': bottle.id
                    })
            return jsonify({'state': 200, 'bottles': data})
        except sqlalchemy.exc.SQLAlchemyError:
            return jsonify({'error': '核废水腐蚀了你的漂流瓶，请稍后重试'})

    return jsonify({'error': '核废水流到了大海，请稍后重试'})
